package checkers;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Runner class for the Flying Moose Checkers game.
 * 
 * @author Ilya
 * 
 */
public class Runner {

	/**
	 * Flag to enable debugging output to the console.
	 */
	private static boolean DEBUG = false;

	/**
	 * Flag to enable error output to the console.
	 */
	private static boolean SHOW_ERRORS = false;

	/**
	 * Runs the Flying Moose Checkers game.
	 * 
	 * @param args
	 *            Takes in arguments "-d" and/or "-e", to enable debug
	 *            statements and errors, respectively.
	 */
	public static void main(String[] args) {

		File f = new File("singlelock");
		if (f.exists()) {
			System.err
					.println("Instance of this game is already running.\n"
							+ "If not, delete the 'singlelock' file in the game directory.\n"
							+ "Enter the letter 'y' to continue anyway. Any enter key to exit.");
			Scanner s = new Scanner(System.in);
			String response = s.nextLine();
			if (response.trim().toLowerCase().equals("y")) {
				//let them continue
			} else {
				System.exit(-1);
			}
		}
		try {
			f.createNewFile();

		} catch (IOException e) {
			//
		}

		System.out
				.println("You acknowledge that this software is not designed, \n"
						+ "licensed or intended for use in the design, construction, \n"
						+ "operation or maintenance of any nuclear facility.");

		// Does flaggy stuff from commandline
		{
			// trims all non alpha symbols from args
			for (int i = 0; i < args.length; i++) {
				args[i] = args[i].toLowerCase().replaceAll("[^a-z]", "");
			}

			// sort array for accurate binarySearch
			Arrays.sort(args);

			if (Arrays.binarySearch(args, "d") >= 0) {
				DEBUG = true;
				SHOW_ERRORS = true;
				System.out.println("Debugging is Enabled.");
			} else if (Arrays.binarySearch(args, "e") >= 0) {
				SHOW_ERRORS = true;
				System.err.println("Errors are Enabled.");
			}

			// This silences the Batman (if not debuging).
			if (!DEBUG) {
				System.setOut(new PrintStream(new ByteArrayOutputStream()));
			}

			// If you don't know what this does.
			if (!SHOW_ERRORS) {
				System.setErr(new PrintStream(new ByteArrayOutputStream()));
			}
		}

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				GameUI.createAndShowGUI();
			}
		});

	}

}
